package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApLikesBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.exception.CustomException;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class ApLikesBehaviorServiceimpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements ApLikesBehaviorService {
    @Resource
    ApBehaviorEntryService apBehaviorEntryService;

    //参数校验
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {

        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //获取登录用户
        ApUser user = AppThreadLocalUtils.getUser();
        //查询行为实体是否存在
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());

        if (apBehaviorEntry == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApLikesBehavior likesBehavior = this.getOne(Wrappers.<ApLikesBehavior>lambdaQuery().eq(ApLikesBehavior::getEntryId, apBehaviorEntry.getId()).eq(ApLikesBehavior::getArticleId, dto.getArticleId()));

        if (likesBehavior == null) {
            //封装添加参数
            ApLikesBehavior apLikesBehavior = new ApLikesBehavior();
            apLikesBehavior.setArticleId(dto.getArticleId());
            apLikesBehavior.setCreatedTime(new Date());
            apLikesBehavior.setEntryId(apBehaviorEntry.getId());
            apLikesBehavior.setOperation(dto.getOperation());
            apLikesBehavior.setType(dto.getType());

            //添加
            this.save(apLikesBehavior);

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } else {
            //取消点赞
            likesBehavior.setOperation(dto.getOperation());
            this.updateById(likesBehavior);

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

    }
}
